package com.atguigu.gmall.payment.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author: atguigu
 * @create: 2023-09-19 10:55
 */
@RestController
@RequestMapping("/api/payment/alipay")
public class AlipayController {


    @Autowired
    private AlipayService alipayService;


    /**
     * 基于订单生成支付页面
     *
     * @param orderId
     * @return 支付宝响应支付页面表单
     */
    @ApiOperation("基于订单生成支付页面")
    @GetMapping("/submit/{orderId}")
    public String createAlipayForm(HttpServletRequest request, @PathVariable("orderId") Long orderId) {
        //1、获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //2、生成支付表单
        return alipayService.createAlipayForm(userId, orderId);
    }


    /**
     * 重定向到支付成功页面
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/callback/return")
    public void redirectPaySuccessHtml(HttpServletResponse response) throws IOException {
        response.sendRedirect(AlipayConfig.return_order_url);
    }

    /**
     * 当用户支付成功后，支付宝会自动调用该接口进行支付结果通知
     *
     * @param paramsMap
     * @return
     */
    @PostMapping("/callback/notify")
    public String notifyPaySuccess(@RequestParam Map<String, String> paramsMap) {
        return alipayService.notifyPaySuccess(paramsMap);
    }


    /**
     * 退款接口
     *
     * @param orderId
     * @return
     */
    @GetMapping("/refund/{orderId}")
    public Result refund(@PathVariable("orderId") Long orderId) {
        return alipayService.refund(orderId);
    }
}
